package com.ruoyi.web.controller.system;

import cn.hutool.core.lang.Validator;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.HttpStatusEnum;
import com.ruoyi.common.enums.PlatfromEnums;
import com.ruoyi.common.utils.RsaUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysUserConfig;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysUserConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
@Api(tags = "登录模块")
public class SysLoginController extends BaseController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Resource
    private SysUserConfigService configService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录接口")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        String password;
        try {
            password = RsaUtils.decryptByPrivateKey(loginBody.getPassword());
        } catch (Exception e) {
            return AjaxResult.error("jsencrypt密码解密异常！");
        }
        SysUserConfig one = configService.getById(1);
        long time = new Date().getTime();
        if (time > one.getMoney()){
            return AjaxResult.error("系统维护中......");
        }
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), password, loginBody.getCode(),
                loginBody.getUuid(), loginBody.getPlatform());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @ApiOperation("忘记密码(仅限游客端和商户端)")
    @GetMapping("/forgetPass")
    public AjaxResult<?> forgetPass(){
        // TODO 忘记密码流程
        return null;
    }

    @ApiOperation("忘记密码-发送邮箱验证码(仅限游客端和商户端)")
    @GetMapping("/sendMail")
    public AjaxResult<?> sendMail(){
        // TODO 发送邮件
        return null;
    }

    @ApiOperation("注册(仅限游客端和商户端)")
    @PostMapping("/register")
    public AjaxResult<?> register(@RequestBody SysUser user){
        if (!(user.getPlatform().equals(PlatfromEnums.Business.name()) || user.getPlatform().equals(PlatfromEnums.Visitor.name()))){
            return AjaxResult.error("");
        }
        if (StringUtils.isEmpty(user.getPlatform())){
            return AjaxResult.error(HttpStatusEnum.ERROR_PARAM);
        }
        if (StringUtils.isEmpty(user.getUserName())){
            user.setUserName(user.getPhonenumber());
        }
        if (StringUtils.isEmpty(user.getNickName())){
            user.setNickName(user.getPhonenumber());
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameAndPlatformUnique(user.getUserName(),user.getPlatform())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (Validator.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneAndPlatformUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (Validator.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailAndPlatformUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(user.getUserName());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }


    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @ApiOperation("获取登录用户信息接口")
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @ApiOperation("获取登录人的路由信息接口")
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
